<script setup lang="ts">
// This starter template is using Vue 3 <script setup> SFCs
// Check out https://vuejs.org/api/sfc-script-setup.html#script-setup
import * as  XLSX from 'xlsx'
import { getfiletodata } from './b';
import { computed, reactive, ref, watch } from 'vue';

const data = ref<XLSX.WorkBook>()

const remarks = ref<[number, string]>()

const remarkstext = ref('')

const SheetName = ref<string>()

const SheetNames = computed<string[]>(() => {
  if (!data.value) return []
  return data.value?.SheetNames
})

const table = ref<Record<string, string>[]>([])
const header = ref<string[]>([])


watch(() => SheetName.value, e => {
  table.value = XLSX.utils.sheet_to_json(data.value?.Sheets[SheetName.value], {
    header: 'A',
    blankrows: true,
  })
  // const n = table.value.map(e => {
  //   return Object.keys(e)
  // })
  // header.value = n.flat().sort()
})

watch(() => remarks.value, e => {
  if (e) {
    const [index, i] = e
    const r = data.value?.Sheets[SheetName.value][`${i}${index + 1}`].c
    if (r) {
      remarkstext.value = r[0].t
    } else {
      remarkstext.value = ''
    }
  }

})



async function change(e: Event) {
  const file = e.target.files[0]
  data.value = await getfiletodata(file)
}

function save() {
  const [index, i] = remarks.value
  const r = data.value?.Sheets[SheetName.value][`${i}${index + 1}`].c
  if (r) {
    data.value.Sheets[SheetName.value][`${i}${index + 1}`].c[0] = {
      t: remarkstext.value,
      a: 'name'
    }
  } else {
    if (!data.value.Sheets[SheetName.value][`${i}${index + 1}`].c) {
      data.value.Sheets[SheetName.value][`${i}${index + 1}`].c = []
    }
    data.value.Sheets[SheetName.value][`${i}${index + 1}`].c[0] = {
      t: remarkstext.value,
      a: 'name'
    }

  }
}

function download() {
  if (data.value) {
    // @ts-ignore
    XLSX.write(data.value, { type: "file", bookType: "xlsx", file: `123.xlsx` });
  }
}

</script>

<template>
  <div>
    <input type="file" @change="change">
    <hr>
    <textarea placeholder="标注" rows="10" v-model="remarkstext" @change="save"></textarea>
    <button type="button" @click="download">下载</button>
    <hr>
    选择工作表
    <select v-model="SheetName">
      <option v-for="item in SheetNames" :value="item">{{ item }}</option>
    </select>
    <hr>
    <table border>
      <tr v-for="(item, index) in table">
        <td v-for="(v, i) in item" @click="remarks = [index, i]">
          {{ v }}
        </td>
      </tr>
    </table>
  </div>
</template>
